package com.cloudoer.blog.util;

import com.cloudoer.blog.exception.ServiceException;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
public class FileUtil {
    @Value("${cloudoer.service}")
    private String service;
    @Value("${cloudoer.root}")
    private String rootPath;

    static final String[] FILE_TYPE = { "bmp", "jpg", "jpeg", "png", "tiff", "gif", "pcx", "tga", "exif", "fpx", "svg", "psd",
            "cdr", "pcd", "dxf", "ufo", "eps", "ai", "raw", "wmf", "txt", "doc", "docx", "xls", "rtf", "wpd", "zip", "gz", "rar",
            "pdf", "ppt","mp4", "avi", "mov", "wmv", "asf", "navi", "3gp", "mkv", "f4v", "rmvb", "webm", "mp3", "wma", "wav",
            "mod", "ra", "cd", "md", "asf", "aac", "vqf", "ape", "mid", "ogg", "m4a", "vqf", "7z"};

    /**
     * 删除文件夹
     * @param path
     * @return
     */
    public String deleteImg (String path){
        File file = new File(rootPath + File.separator + path);
        if (file != null && file.exists()){
            deleteAll(file);
        }
        return "操作成功";
    }

    /**
     * 根据URL删除文件
     * @param url
     * @return
     */
    public String deleteFileByURL (String url){
        String path = url.replace(service, rootPath);
        File file = new File(path);
        if (file.isFile()){
            file.delete();
        }
        return "操作成功";
    }

    /**
     * 上传图片
     * @param multipartFile
     * @param folderName
     * @param fileName
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String uploadFile(MultipartFile multipartFile, String folderName, String fileName) throws ServletException, IOException {
        if(multipartFile.isEmpty() && multipartFile.getOriginalFilename()!="" && multipartFile.getSize() > 0){
            throw new ServletException("上传失败，文件为空！");
        }
        //1024*1024*1024*10  ==  10Mb
        if(multipartFile.getSize() > 1024*1024*500){
            //System.out.println((long) multipartFile.getSize());
            throw new ServletException("上传失败，文件大于500M");
        }
        //获取到后缀
        String prefix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".")+1);
        if (!prefix(FILE_TYPE, prefix)){
            throw new ServletException("上传失败，不是指定的类型");
        }
        File file = new File(rootPath + File.separator + folderName);
        if(!file.isDirectory()){
            file.mkdir();
        }
        String path = folderName + File.separator + fileName + "." + prefix;
        multipartFile.transferTo(new File(rootPath + File.separator + path));
        return service + "/" + path;
    }

    /**
     * 按比例压缩图片
     * @param url
     * @param folderName
     * @param fileName
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String compressImg (String url, String folderName, String fileName) throws ServletException, IOException {
        String path = folderName + File.separator + fileName + ".png";
        Thumbnails.of(url.replace(service, rootPath)).size(360,360).keepAspectRatio(true).toFile(rootPath + File.separator + path);
        return service + "/" + path;
    }

    public File getFile (String url){
        String path = url.replace(service, rootPath);
        File file = new File(path);
        if (file.isFile()){
            return file;
        }
        throw new ServiceException("找不到文件");
    }

    /**
     * 校验后缀名
     * @param type
     * @param prefix
     * @return
     */
    private boolean prefix (String[] type, String prefix){
        for (String string : type){
            if (prefix.toLowerCase().equals(string.toLowerCase())){
                return true;
            }
        }
        return false;
    }

    /**
     * 递归删除文件夹及文件夹下所有文件
     * @param file
     * @return
     */
    private boolean deleteAll (File file){
        if (file.isDirectory()) {
            String[] children = file.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteAll(new File(file, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return file.delete();
    }

}
